/*
 * Copyright (C) 2013 Chen Hui <calmer91@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.harmonyos.fishbun;

import com.harmonyos.fishbun.slice.WithActivityAbilitySlice;
import com.harmonyos.fishbun.util.Constant;
import com.sangcomz.fishbun.FishBun;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.event.commonevent.CommonEventData;
import ohos.event.commonevent.CommonEventManager;
import ohos.rpc.RemoteException;
import ohos.utils.net.Uri;
import java.util.ArrayList;

public class WithActivityAbility extends Ability {

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setMainRoute(WithActivityAbilitySlice.class.getName());
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        super.onAbilityResult(requestCode, resultCode, resultData);
        try {
            if (resultData == null) {
                return;
            }
            Intent intent = new Intent();
            Operation operation = new Intent.OperationBuilder()
                    .withAction(Constant.WITH_ACTIVITY_RESULT)
                    .build();
            intent.setParam(Constant.REQUEST_CODE, requestCode);
            intent.setParam(Constant.RESULT_CODE, resultCode);
            ArrayList<Uri> param = resultData.getSerializableParam(FishBun.INTENT_PATH);
            ArrayList<String> data = new ArrayList<>();
            if (param != null) {
                for (Uri uri : param) {
                    data.add(uri.toString());
                }
            }
            intent.setParam(Constant.RESULT_DATA, data);
            intent.setOperation(operation);
            CommonEventData eventData = new CommonEventData(intent);
            CommonEventManager.publishCommonEvent(eventData);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}
